//通用IPC
const {
	app,
	BrowserWindow,
	ipcMain,
	clipboard,
	screen,
	dialog,
} = require("electron");
const path = require("node:path");
const windowConfigs = require("../modulesConfig");
const fs = require("fs");
const browserWindows = {};
const browserHandler = {};
//是否是测试环境
const isDevelopment = !app.isPackaged;

/**
 * 定义了一些通用的IPC监听
 * GENERAL-OPEN-WINDOW : 开启功能窗口
 * GENERAL-SUB-WINDOW-OPEN : 打开父子窗口
 * GENERAL-CLIPBOARD : 复制到剪贴板
 * GENERAL-BAR : 标题栏操作
 */

module.exports = () => {
	//异步：监听开启功能窗口
	ipcMain.on("GENERAL-OPEN-WINDOW", (event, arg) => {
		if (!arg) return;
		const { id } = arg;
		let browserWindow = browserWindows[id];
		if (browserWindow) {
			//如果目标窗口已经开启，则激活显示
			if (browserWindow.isMinimized()) {
				browserWindow.restore();
			}
			browserWindow.focus();
			browserWindow.show();
			return;
		}
		const { config, hash, dev, maximize } = windowConfigs[id];
		browserWindow = new BrowserWindow({
			...config,
			show: false,
			icon: path.join(__dirname, "../assets/PlantB.ico"),
			webPreferences: {
				preload: path.join(__dirname, "../preload.js"),
			},
		});

		if (maximize) {
			browserWindow.maximize();
		}

		browserWindow.once("ready-to-show", () => {
			browserWindow.show();
		});

		if (!config.frame) {
			if (isDevelopment) {
				browserWindow.loadURL(path.join("http://localhost:7758", hash));
			} else {
				browserWindow.loadFile(path.join(__dirname, "../platform/index.html"), {
					hash,
				});
			}
		} else {
			browserWindow.loadURL(config.frame);
		}

		if (dev) {
			//是否开启调试
			browserWindow.webContents.openDevTools();
		}
		browserWindow.on("close", () => {
			browserWindows[id] = null;
		});

		//监听系统操作回调
		browserWindow.on("unmaximize", () => {
			browserHandler[id]?.reply("UNMAXIMIZE-CALL");
		});

		browserWindow.on("maximize", () => {
			browserHandler[id]?.reply("MAXIMIZE-CALL");
		});

		browserWindows[id] = browserWindow;
	});

	//异步：监听每个窗口的初始化，并保存其handler
	ipcMain.on("GENERAL-INIT-WINDOW", (event, arg) => {
		const { id } = arg;
		browserHandler[id] = event;
	});

	//异步：监听打开父子窗口
	ipcMain.on("GENERAL-SUB-WINDOW-OPEN", (event, arg) => {
		const { config } = arg;
		const window = BrowserWindow.getFocusedWindow();
		browserWindow = new BrowserWindow({
			...config,
			show: false,
			backgroundColor: "#00000000",
			titleBarStyle: "hidden",
			frame: false,
			resizable: false,
			parent: window,
			modal: true,
			webPreferences: {
				preload: path.join(__dirname, "../preload.js"),
			},
			x: Math.round(
				(screen.getPrimaryDisplay().workAreaSize.width - config.width) / 2
			),
			y: Math.round(
				(screen.getPrimaryDisplay().workAreaSize.height - config.height) / 2
			),
		});
		// browserWindow.webContents.openDevTools();
		browserWindow.once("ready-to-show", () => {
			browserWindow.show();
		});
		if (isDevelopment) {
			browserWindow.loadURL(path.join("http://localhost:7758", config.hash));
		} else {
			browserWindow.loadFile(path.join(__dirname, "../platform/index.html"), {
				hash: config.hash,
			});
		}
	});

	//同步：监听复制到剪贴板
	ipcMain.on("GENERAL-CLIPBOARD", (event, arg) => {
		const { type, value } = arg;
		if (type == "text") {
			clipboard.writeText(value);
		}
	});

	//异步：监听标题栏操作
	ipcMain.on("GENERAL-BAR-OPERATE", function (event, arg) {
		const { mark } = arg;
		const window = BrowserWindow.getFocusedWindow();
		switch (mark) {
			case "close":
				window.close();
				break;
			case "maximize":
				window.maximize();
				break;
			case "minimize":
				window.minimize();
				break;
			case "restore":
				window.restore();
				break;
			default:
				break;
		}
	});

	//监听选择路径并储存
	ipcMain.on("GENERAL-SAVE-AS", (event, arg) => {
		const { title, filename, data } = arg;
		dialog
			.showSaveDialog({
				title,
				buttonLabel: "保存",
				defaultPath: filename, // 默认文件名
				filters: [{ name: "JPG Files", extensions: ["jpg"] }],
			})
			.then(({ filePath }) => {
				if (filePath) {
					const buffer = Buffer.from(data.replace(/^.*base64,/, ""), "base64");
					fs.writeFile(filePath, buffer, (err) => {
						if (err) {
							console.log("保存图片错误", err);
							return;
						}
						dialog.showMessageBox({
							title: "提示",
							message: "保存成功",
							detail: "已经保存至" + filePath,
						});
					});
				}
			});
	});
};
